﻿using Newtonsoft.Json.Serialization;
using RuoVea.ExFilter;
using RuoVea.ExIdGen;
using RuoVea.ExJwtBearer;
using RuoVea.ExSugar;
using RuoVea.OmiApi.UserRoleMenu.Entitys;
using RuoVea.OmiConfig;
using RuoVea.OmiConfig.Extensions;
using RuoVea.OmiLog;
using RuoVea.OmiLogin;
using RuoVea.OmiReports;
using RuoVea.OmiUserRoleMenu;
using RuoVea.Report.Web.Filters;
using System.Diagnostics;

namespace RuoVea.Report.Web;
public class Program
{
    public static async Task Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddLocalization();

        // Add services to the container.
        builder.Services.AddControllersWithViews(options => options.Filters.Add<GlobalAuthorizeFilter>())
            .AddNewtonsoftJson(options =>
            {
                //不使用驼峰命名样式
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

        // 从配置中获取
        builder.Services.Configure<SystemInfo>(builder.Configuration.GetSection("SystemInfo"));

        builder.Services
            .AddHttpContextSetup<AspNetUser>()
            .AddOmiConfigSetup()
            .AddOmiReportSetup()
            .AddOmiLogSetup()
            .AddOmiSystemSetup()
            .AddOmiLoginSetup(o =>
            {
                o.DefaultUrl = "/Home";
                o.RedirectUrl = "/Home";
                o.LoginPath = "/auth/login";
                o.Scheme = "RuoVea.Report:" + o.Scheme;
                o.ShowI18n = true;
            });

        builder.Services
            .AddSqlSugarSetup();

        builder.Services
            .AddConfigInitSetup()
            //.AddAuthInitSetup()
            .AddLogInitSetup()
            .AddReportInitSetup()
            .AddSystemInitSetup();

        //builder.Services.AddDictInitSetup();/*需要在 AddSqlSugarSetup之后*/

        //builder.Services.AddInjectServiceSetup("RuoVea.Report.Server");

        builder.Services
            .AddRestfulSetup<CustomizeFilterLog>()
            .RequestActionSetup() // 注入 请求日志拦截 [执行操作日志、参数验证 ]
            .ResultSetup()
            .ExceptionSetup();

        var app = builder.Build();

        app.UseOmiLocalization();

        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        //app.UseStatusCodePagesWithReExecute("/Error/{0}");
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseOmiLocalization();
        app.UseRouting();

        app.UseOmiLogUI()
            .UseOmiConfigUI()
            .UseOmiReportUI()
            .UseOmiSystemUI()
            .UseOmiLoginUI();

        app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

        // 初始化数据库表
        await Task.Run(async () =>
        {
            var _thisRepository = app.Services.GetRequiredService<ISqlSugarClient>();
           var hasData= _thisRepository.Queryable<SysMenu>().Where(x => x.Name == "rpt").Any();
            if (!hasData)
            {
                long id = IdGenerator.Id;
                _thisRepository.Insertable(new List<SysMenu> {
                new SysMenu{  Id=id, IsDelete=0,IsDisable=0,Sort=500,IsAffix=false,IsHide=false,  IsIframe=false,Icon="el-icon-data-board",Title="报表",Name="rpt",Type=0,Pid=0 },

                 new SysMenu{  Id=IdGenerator.Id, IsDelete=0,IsDisable=0,Sort=100,IsAffix=false,IsHide=false,  IsIframe=false,Icon="el-icon-connection",Title="数据源",Name="rptdatabase",Path="/rptdatabase/index", Type= ExEnum.MenuType.MENU,Pid=id },

                 new SysMenu{  Id=IdGenerator.Id, IsDelete=0,IsDisable=0,Sort=100,IsAffix=false,IsHide=false,  IsIframe=false,Icon="el-icon-connection",Title="报表设计",Name="rptsql",Path="/rptsql/index", Type= ExEnum.MenuType.MENU,Pid=id },
                }).ExecuteCommand();
            }

            // 检查命令行参数
            if (args.Contains("--open"))
            {
                var httpUrl = builder.Configuration.GetValue<string>("Url");// 设置默认监听地址
                if (string.IsNullOrEmpty(httpUrl)) return;
                builder.WebHost.UseUrls(httpUrl);
                try { Process.Start(new ProcessStartInfo(httpUrl) { UseShellExecute = true }); }
                catch { using var client = new HttpClient(); await client.GetAsync(httpUrl); }
            }
        });

        app.Run();
    }
}